using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using MySql.Data.MySqlClient;
using System.Collections.Generic;

namespace Weather
{
    public partial class MoodHistoryForm : Form
    {
        private FlowLayoutPanel calendarPanel;
        private ComboBox cmbMonth;
        private Label lblYear;
        private Dictionary<string, string> moodEmojis = new Dictionary<string, string>()
        {
            { "开心", "😊" },
            { "平静", "😌" },
            { "难过", "😢" },
            { "生气", "😠" },
            { "焦虑", "😰" }
        };

        private Dictionary<string, Color> moodBackColors = new Dictionary<string, Color>()
        {
            { "开心", Color.FromArgb(240, 255, 240) }, // 淡绿色
            { "平静", Color.FromArgb(240, 248, 255) }, // 淡蓝色
            { "难过", Color.FromArgb(255, 240, 245) }, // 淡粉色
            { "生气", Color.FromArgb(255, 245, 238) }, // 淡橙色
            { "焦虑", Color.FromArgb(255, 250, 240) }  // 淡黄色
        };

        public MoodHistoryForm()
        {
            InitializeComponents();
            LoadMoodHistory();
        }

        private void InitializeComponents()
        {
            this.Size = new Size(800, 600);
            this.BackColor = Color.White;
            this.Padding = new Padding(20);

            // 创建顶部面板
            var topPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 50,
                Padding = new Padding(10)
            };

            // 年份标签
            lblYear = new Label
            {
                Text = DateTime.Now.Year.ToString(),
                Font = new Font("Microsoft YaHei", 16, FontStyle.Bold),
                AutoSize = true,
                Location = new Point(10, 10)
            };

            // 月份选择
            cmbMonth = new ComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("Microsoft YaHei", 12),
                Location = new Point(100, 12),
                Width = 120
            };

            string[] months = { "一月", "二月", "三月", "四月", "五月", "六月", 
                              "七月", "八月", "九月", "十月", "十一月", "十二月" };
            cmbMonth.Items.AddRange(months);
            cmbMonth.SelectedIndex = DateTime.Now.Month - 1;
            cmbMonth.SelectedIndexChanged += (s, e) => LoadMoodHistory();

            topPanel.Controls.AddRange(new Control[] { lblYear, cmbMonth });

            // 创建日历面板
            calendarPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Padding = new Padding(10),
                BackColor = Color.FromArgb(245, 247, 250)
            };

            // 添加星期标题
            string[] weekDays = { "日", "一", "二", "三", "四", "五", "六" };
            foreach (string day in weekDays)
            {
                var dayLabel = new Label
                {
                    Text = day,
                    TextAlign = ContentAlignment.MiddleCenter,
                    Font = new Font("Microsoft YaHei", 10),
                    Size = new Size(100, 30),
                    Margin = new Padding(5),
                    ForeColor = Color.FromArgb(64, 64, 64)
                };
                calendarPanel.Controls.Add(dayLabel);
            }

            this.Controls.Add(calendarPanel);
            this.Controls.Add(topPanel);
        }

        private void LoadMoodHistory()
        {
            try
            {
                // 清除现有的日期格子（保留星期标题）
                while (calendarPanel.Controls.Count > 7)
                {
                    calendarPanel.Controls.RemoveAt(7);
                }

                // 获取选中月份的第一天
                int year = int.Parse(lblYear.Text);
                int month = cmbMonth.SelectedIndex + 1;
                var firstDay = new DateTime(year, month, 1);

                // 添加月初的空白格子
                int startDayOfWeek = (int)firstDay.DayOfWeek;
                for (int i = 0; i < startDayOfWeek; i++)
                {
                    AddEmptyDay();
                }

                // 获取当月的心情数据
                var moodData = GetMonthMoodData(year, month);

                // 添加日期格子
                int daysInMonth = DateTime.DaysInMonth(year, month);
                for (int day = 1; day <= daysInMonth; day++)
                {
                    var date = new DateTime(year, month, day);
                    MoodData mood = null;
                    if (moodData.ContainsKey(day))
                    {
                        mood = moodData[day];
                    }
                    AddDayCell(day, mood);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private Dictionary<int, MoodData> GetMonthMoodData(int year, int month)
        {
            var result = new Dictionary<int, MoodData>();
            string sql = @"
                SELECT 
                    DAY(created_at) as day,
                    mood_type,
                    content
                FROM user_moods
                WHERE user_id = @userId
                    AND YEAR(created_at) = @year
                    AND MONTH(created_at) = @month";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@userId", MySqlDbType.Int32) { Value = CurrentUser.Id },
                new MySqlParameter("@year", MySqlDbType.Int32) { Value = year },
                new MySqlParameter("@month", MySqlDbType.Int32) { Value = month }
            };

            try
            {
                var dt = DBHelper.ExecuteQuery(sql, parameters);
                foreach (DataRow row in dt.Rows)
                {
                    int day = Convert.ToInt32(row["day"]);
                    result[day] = new MoodData
                    {
                        Type = row["mood_type"].ToString(),
                        Content = row["content"].ToString()
                    };
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取心情数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return result;
        }

        private void AddEmptyDay()
        {
            var emptyCell = new Panel
            {
                Size = new Size(100, 100),
                Margin = new Padding(5),
                BackColor = Color.Transparent
            };
            calendarPanel.Controls.Add(emptyCell);
        }

        private void AddDayCell(int day, MoodData mood)
        {
            var cell = new Panel
            {
                Size = new Size(100, 100),
                Margin = new Padding(5),
                BackColor = Color.White,
                Padding = new Padding(5)
            };

            // 添加日期标签
            var lblDay = new Label
            {
                Text = day.ToString(),
                Font = new Font("Microsoft YaHei", 12),
                Location = new Point(5, 5),
                AutoSize = true,
                ForeColor = Color.FromArgb(64, 64, 64)
            };
            cell.Controls.Add(lblDay);

            if (mood != null)
            {
                // 设置背景色
                cell.BackColor = moodBackColors.ContainsKey(mood.Type) ? 
                    moodBackColors[mood.Type] : Color.White;

                // 添加表情符号标签
                var lblEmoji = new Label
                {
                    Text = moodEmojis.ContainsKey(mood.Type) ? moodEmojis[mood.Type] : "😐",
                    Font = new Font("Segoe UI Emoji", 24),
                    Size = new Size(60, 60),
                    Location = new Point(20, 25),
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent // 确保表情符号标签背景透明
                };

                // 添加工具提示
                var tooltip = new ToolTip();
                tooltip.SetToolTip(lblEmoji, $"心情：{mood.Type}\n{mood.Content}");

                cell.Controls.Add(lblEmoji);

                // 添加点击事件以显示详细信息
                cell.Click += (s, e) => 
                {
                    MessageBox.Show(
                        $"日期：{new DateTime(int.Parse(lblYear.Text), cmbMonth.SelectedIndex + 1, day):yyyy年MM月dd日}\n" +
                        $"心情：{mood.Type}\n" +
                        $"内容：{mood.Content}",
                        "心情详情",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information
                    );
                };
                
                // 让整个单元格可点击
                cell.Cursor = Cursors.Hand;

                // 添加鼠标悬停效果
                cell.MouseEnter += (s, e) => 
                {
                    cell.BackColor = ChangeColorBrightness(moodBackColors[mood.Type], -0.1f);
                };
                
                cell.MouseLeave += (s, e) => 
                {
                    cell.BackColor = moodBackColors[mood.Type];
                };
            }

            // 添加边框效果
            cell.Paint += (s, e) =>
            {
                var bounds = new Rectangle(0, 0, cell.Width - 1, cell.Height - 1);
                using (var pen = new Pen(Color.FromArgb(230, 230, 230)))
                {
                    e.Graphics.DrawRectangle(pen, bounds);
                }
            };

            calendarPanel.Controls.Add(cell);
        }

        // 辅助方法：调整颜色亮度
        private Color ChangeColorBrightness(Color color, float correctionFactor)
        {
            float red = color.R;
            float green = color.G;
            float blue = color.B;

            if (correctionFactor < 0)
            {
                correctionFactor = 1 + correctionFactor;
                red *= correctionFactor;
                green *= correctionFactor;
                blue *= correctionFactor;
            }
            else
            {
                red = (255 - red) * correctionFactor + red;
                green = (255 - green) * correctionFactor + green;
                blue = (255 - blue) * correctionFactor + blue;
            }

            return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
        }

        // 添加一个 MoodData 类来存储心情数据
        public class MoodData
        {
            public string Type { get; set; }    
            public string Content { get; set; }
        }
    }
} 